package com.dong.mjblog.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dong.mjblog.dto.AccessTokenDTO;
import com.dong.mjblog.dto.UserDTO;
import com.dong.mjblog.entity.UserEntity;
import com.dong.mjblog.provider.GithubProvider;
import com.dong.mjblog.service.impl.UserImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @Author:dxf
 * @Date:2020/10/3-10-03 22:40
 */
@Controller
public class AuthorizeController {

    @Autowired
    private GithubProvider githubProvider;

    @Value("${github.client.id}")
    private String clientId;

    @Value("${github.client.secret}")
    private String clientSecret;

    @Value("${github.redirect.url}")
    private String redirectUrl;

    @Autowired
    private UserImpl userImpl;

    @GetMapping("/callback")
    public String callback(@RequestParam(name = "code") String code,
                           @RequestParam(name = "state") String state,
                           HttpServletResponse response) {
        AccessTokenDTO accessTokenDTO = new AccessTokenDTO();
        accessTokenDTO.setClient_id(clientId);
        accessTokenDTO.setClient_secret(clientSecret);
        accessTokenDTO.setCode(code);
        accessTokenDTO.setRedirect_uri(redirectUrl);
        accessTokenDTO.setState(state);
        String accessToken = githubProvider.getAccessToken(accessTokenDTO);
//        System.out.println(accessToken);
        UserDTO user = githubProvider.getUser(accessToken);
//        System.out.println(user.getId());
        if (user != null) {
            String accountId = String.valueOf(user.getId());
            String token = UUID.randomUUID().toString();
            UserEntity one = userImpl.getOne(Wrappers.<UserEntity>lambdaQuery().eq(UserEntity::getAccountId, accountId), false);
            Long timestamp = System.currentTimeMillis() / 1000;
            if (one == null) {

                //登录成功
                UserEntity userEntity = new UserEntity();
                userEntity.setName(user.getLogin());
                userEntity.setAccountId(accountId);
                userEntity.setToken(token);
                userEntity.setAvatarUrl(user.getAvatar_url());
                userEntity.setGmtCreate(timestamp);
                userEntity.setGmtModified(timestamp);
                boolean result = userImpl.save(userEntity);
            }else{
                one.setToken(token);
                one.setAvatarUrl(user.getAvatar_url());
                one.setName(user.getLogin());
                one.setGmtModified(timestamp);
                boolean result = userImpl.updateById(one);
            }
            response.addCookie(new Cookie("token", token));
//            request.getSession().setAttribute("user",user);
        } else {
            //TODO 抛出报错消息
            //登录失败
        }
        return "redirect:/";
    }

    @GetMapping("/logout")
    public String logout(HttpServletRequest request,
                         HttpServletResponse response) {
        System.out.println(222);
        request.getSession().removeAttribute("user");
        //清空cookie
        Cookie cookie = new Cookie("token",null);
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        return "redirect:/";
    }
}
